﻿package com.webbei.HAO.action;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.struts2.ServletActionContext;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.opensymphony.xwork2.ActionContext;
import com.webbei.util.StringUtil;

public class SendMsgToEmailAction {
    private JavaMailSender sender;
	public String email;
	public String msg;

	public String execute() {
		try {
			System.out.println("send....."+email);
			send();
			ServletActionContext.getResponse().getWriter().write("success");
			ServletActionContext.getResponse().setContentType("text/html");
		} catch (MessagingException e) {
			System.out.println("exception.....");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	public void send() throws MessagingException {
		// 获取JavaMailSender bean
		JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
		MimeMessage mailMessage = senderImpl.createMimeMessage();
		// 设置utf-8或GBK编码，否则邮件会有乱码
		MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,
				true, "utf-8");
		try {

			messageHelper.setTo(email);// 接受者
			messageHelper.setFrom("yanxing12742@foxmail.com");// 发送者
			messageHelper.setSubject("网贝账号");// 主题
			// 邮件内容，注意加参数true，表示启用html格式
			String randomString = StringUtil.getRandomString(30);
			ActionContext.getContext().getSession().put("key", randomString);
			messageHelper
					.setText(
							"<html><head></head><body>修改密码请点这里<a href=http://test.com:8080/webbei/newPwd.jsp?email="+email+"&&key="+randomString+" >修改密码</a></body></html>",
							true);
			sender.send(mailMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public JavaMailSender getSender() {
		return sender;
	}

	public void setSender(JavaMailSender sender) {
		this.sender = sender;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

}